package com.cy.service.factory;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class DefaultBlockException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        //设置响应数据的编码
        response.setCharacterEncoding("utf-8");
        //告诉客户端要响应的数据类型以及客户端亿什么编码呈现数据
        response.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter=response.getWriter();
        //创建map集合来封装返回的数据
        Map<String,Object> map=new HashMap<>();

        if (e instanceof DegradeException) { //熔断，就降级

            map.put("status", 601);
            map.put("message", "服务被熔断或者降级了");

        }else if (e instanceof FlowException) {//服务被限流了 。请小心使用。慢点
            map.put("status", 602);
            map.put("message", "服务被限流了");


        }else if (e instanceof ParamFlowException) {
            map.put("status", 604);
            map.put("message", "服务被热点先溜了。请注意你的访问量");


        }
        else {
            map.put("status", 603);
            map.put("message", "Blocked by Sentinel (flow limiting)");

        }
         //将数据写到前段
        String jason=new ObjectMapper().writeValueAsString(map);
        printWriter.println(jason);
        printWriter.flush();



    }
}
